<template>
  <div class="schedule-management">
    <div class="page-header">
      <h2>⏰ 会议室时间表管理</h2>
      <a-button type="primary" @click="showAddModal">
        <PlusOutlined /> 添加时间表
      </a-button>
    </div>

    <!-- Room Selector -->
    <a-card style="margin-bottom: 20px">
      <a-select
        v-model:value="selectedRoomId"
        placeholder="选择会议室查看/管理时间表"
        style="width: 300px"
        @change="handleRoomChange"
      >
        <a-select-option v-for="room in rooms" :key="room.id" :value="room.id">
          {{ room.name }}
        </a-select-option>
      </a-select>
      
      <a-button
        v-if="selectedRoomId"
        type="dashed"
        @click="createDefaultSchedule"
        style="margin-left: 10px"
      >
        创建默认时间表 (周一至周五 8:00-18:00)
      </a-button>
    </a-card>

    <!-- Schedules Table -->
    <a-table
      v-if="selectedRoomId"
      :columns="columns"
      :data-source="schedules"
      :loading="loading"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'day_of_week'">
          {{ getDayName(record.day_of_week) }}
        </template>

        <template v-else-if="column.key === 'time_range'">
          {{ record.open_time }} - {{ record.close_time }}
        </template>

        <template v-else-if="column.key === 'is_available'">
          <a-tag :color="record.is_available ? 'green' : 'red'">
            {{ record.is_available ? '可用' : '关闭' }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" size="small" @click="showEditModal(record)">
              编辑
            </a-button>
            <a-button type="primary" danger size="small" @click="handleDelete(record.id)">
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- Add/Edit Schedule Modal -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalMode === 'add' ? '添加时间表' : '编辑时间表'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirm-loading="modalLoading"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="会议室" name="room_id" v-if="modalMode === 'add'">
          <a-select v-model:value="formState.room_id" placeholder="选择会议室">
            <a-select-option v-for="room in rooms" :key="room.id" :value="room.id">
              {{ room.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="星期" name="day_of_week">
          <a-select v-model:value="formState.day_of_week">
            <a-select-option :value="0">周一</a-select-option>
            <a-select-option :value="1">周二</a-select-option>
            <a-select-option :value="2">周三</a-select-option>
            <a-select-option :value="3">周四</a-select-option>
            <a-select-option :value="4">周五</a-select-option>
            <a-select-option :value="5">周六</a-select-option>
            <a-select-option :value="6">周日</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item name="is_available">
          <a-checkbox v-model:checked="formState.is_available">
            该日会议室可用
          </a-checkbox>
        </a-form-item>

        <a-form-item label="开放时间" name="open_time" v-if="formState.is_available">
          <a-time-picker
            v-model:value="formState.open_time"
            format="HH:mm"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item label="关闭时间" name="close_time" v-if="formState.is_available">
          <a-time-picker
            v-model:value="formState.close_time"
            format="HH:mm"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { getRooms } from '@/services/roomService'
import {
  getRoomSchedule,
  createSchedule,
  createDefaultSchedule as apiCreateDefaultSchedule,
  updateSchedule,
  deleteSchedule,
} from '@/services/scheduleService'

const loading = ref(false)
const rooms = ref([])
const schedules = ref([])
const selectedRoomId = ref(null)
const modalVisible = ref(false)
const modalMode = ref('add')
const modalLoading = ref(false)
const formRef = ref(null)
const currentScheduleId = ref(null)

const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

const columns = [
  { title: '星期', key: 'day_of_week' },
  { title: '时间范围', key: 'time_range' },
  { title: '状态', key: 'is_available' },
  { title: '操作', key: 'action', width: 200 },
]

const formState = reactive({
  room_id: null,
  day_of_week: 0,
  open_time: dayjs('08:00', 'HH:mm'),
  close_time: dayjs('18:00', 'HH:mm'),
  is_available: true,
})

const rules = {
  room_id: [{ required: true, message: '请选择会议室' }],
  day_of_week: [{ required: true, message: '请选择星期' }],
  open_time: [{ required: true, message: '请选择开放时间' }],
  close_time: [{ required: true, message: '请选择关闭时间' }],
}

const fetchRooms = async () => {
  try {
    rooms.value = await getRooms()
  } catch (error) {
    message.error('加载会议室列表失败')
  }
}

const fetchSchedules = async () => {
  if (!selectedRoomId.value) return

  loading.value = true
  try {
    schedules.value = await getRoomSchedule(selectedRoomId.value)
  } catch (error) {
    message.error('加载时间表失败')
  } finally {
    loading.value = false
  }
}

const handleRoomChange = () => {
  fetchSchedules()
}

const createDefaultSchedule = async () => {
  try {
    await apiCreateDefaultSchedule(selectedRoomId.value)
    message.success('默认时间表创建成功')
    fetchSchedules()
  } catch (error) {
    message.error(error.response?.data?.detail || '创建默认时间表失败')
  }
}

const showAddModal = () => {
  modalMode.value = 'add'
  modalVisible.value = true
  resetForm()
  if (selectedRoomId.value) {
    formState.room_id = selectedRoomId.value
  }
}

const showEditModal = (schedule) => {
  modalMode.value = 'edit'
  currentScheduleId.value = schedule.id
  formState.room_id = schedule.room_id
  formState.day_of_week = schedule.day_of_week
  formState.open_time = dayjs(schedule.open_time, 'HH:mm:ss')
  formState.close_time = dayjs(schedule.close_time, 'HH:mm:ss')
  formState.is_available = schedule.is_available
  modalVisible.value = true
}

const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    modalLoading.value = true

    const scheduleData = {
      room_id: formState.room_id,
      day_of_week: formState.day_of_week,
      is_available: formState.is_available,
    }

    if (formState.is_available) {
      scheduleData.open_time = formState.open_time.format('HH:mm:ss')
      scheduleData.close_time = formState.close_time.format('HH:mm:ss')
    } else {
      scheduleData.open_time = '00:00:00'
      scheduleData.close_time = '00:00:00'
    }

    if (modalMode.value === 'add') {
      await createSchedule(scheduleData)
      message.success('时间表创建成功')
    } else {
      const updateData = { ...scheduleData }
      delete updateData.room_id // Don't update room_id
      await updateSchedule(currentScheduleId.value, updateData)
      message.success('时间表更新成功')
    }

    modalVisible.value = false
    fetchSchedules()
  } catch (error) {
    if (error.response) {
      message.error(error.response.data.detail || '操作失败')
    }
  } finally {
    modalLoading.value = false
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

const handleDelete = (scheduleId) => {
  Modal.confirm({
    title: '删除时间表',
    content: '确定要删除这个时间表吗？',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await deleteSchedule(scheduleId)
        message.success('时间表删除成功')
        fetchSchedules()
      } catch (error) {
        message.error('删除时间表失败')
      }
    },
  })
}

const resetForm = () => {
  formState.room_id = selectedRoomId.value || null
  formState.day_of_week = 0
  formState.open_time = dayjs('08:00', 'HH:mm')
  formState.close_time = dayjs('18:00', 'HH:mm')
  formState.is_available = true
  formRef.value?.resetFields()
}

const getDayName = (dayNumber) => {
  return dayNames[dayNumber] || ''
}

onMounted(() => {
  fetchRooms()
})
</script>

<style scoped>
.schedule-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #262626;
}
</style>
